/**
 * 认证相关API接口
 * 使用Django内置认证系统
 */
import { apiRequest } from '@/utils/api'

// 获取CSRF Token的辅助函数
function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

// 获取CSRF Token
function getCSRFToken() {
  return getCookie('csrftoken');
}

export const authApi = {
  // Django登录验证 - 前端表单提交到后端验证
  login: async (username, password) => {
    const csrfToken = getCSRFToken();
    
    const response = await fetch('/api/auth/login/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRFToken': csrfToken,  // 添加CSRF Token
      },
      body: JSON.stringify({
        username: username,
        password: password
      }),
      credentials: 'include', // 包含cookies用于Django session
    })
    
    const result = await response.json()
    
    if (response.ok && result.success) {
      return result
    } else {
      throw new Error(result.error || '登录失败')
    }
  },
  
  // Django Session登录 - 重定向到Django登录页面（备用方案）
  loginRedirect: () => {
    window.location.href = '/accounts/login/'
  },
  
  // Django Session登出
  logout: async () => {
    try {
      const response = await fetch('/accounts/logout/', {
        method: 'POST',
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
        },
        credentials: 'include',
      })
      return { success: true }
    } catch (error) {
      throw new Error('登出失败')
    }
  },
  
  // 登出重定向（备用方案）
  logoutRedirect: () => {
    window.location.href = '/accounts/logout/'
  },
  
  // 检查用户认证状态
  checkAuth: async () => {
    try {
      const response = await fetch('/admin/', {
        method: 'GET',
        credentials: 'include',
      })
      return response.ok || response.status === 302
    } catch (error) {
      return false
    }
  },
  
  // 获取当前用户信息
  getCurrentUser: async () => {
    try {
      const response = await fetch('/api/auth/user/', {
        method: 'GET',
        credentials: 'include',
      })
      if (response.ok) {
        return await response.json()
      }
      throw new Error('获取用户信息失败')
    } catch (error) {
      throw error
    }
  },
  
  // 注册功能
  register: (userData) => {
    // 这里可以重定向到Django的注册页面，或者创建一个Django视图来处理
    throw new Error('请联系管理员进行用户注册')
  },
  
  // 密码重置 - 重定向到Django密码重置页面
  resetPassword: () => {
    window.location.href = '/accounts/password_reset/'
  },
  
  // 密码修改 - 重定向到Django密码修改页面
  changePassword: () => {
    window.location.href = '/accounts/password_change/'
  },
}

export default authApi